package com.github_dididipapa.mall.ware.service.impl;

import com.github_dididipapa.common.constant.WareConstant;
import com.github_dididipapa.common.exception.OpenFeignException;
import com.github_dididipapa.mall.ware.entity.PurchaseDetailEntity;
import com.github_dididipapa.mall.ware.service.PurchaseDetailService;
import com.github_dididipapa.mall.ware.service.WareSkuService;
import com.github_dididipapa.mall.ware.vo.MergeVo;
import com.github_dididipapa.mall.ware.vo.PurchaseDoneVo;
import com.github_dididipapa.mall.ware.vo.PurchaseItemDoneVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github_dididipapa.common.utils.PageUtils;
import com.github_dididipapa.common.utils.Query;

import com.github_dididipapa.mall.ware.dao.PurchaseDao;
import com.github_dididipapa.mall.ware.entity.PurchaseEntity;
import com.github_dididipapa.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    @Lazy
    private PurchaseService purchaseService;
    private final PurchaseDetailService purchaseDetailService;
    private final WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //1.如果采购单ID为空，则新建一个
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseService.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //2.确认采购单状态是0或者1才能够合并
        PurchaseEntity entity = purchaseService.getById(purchaseId);
        if(entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> entityList = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(entityList);
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            purchaseService.updateById(purchaseEntity);
        }
    }

    /**
     * @description:
     * @author: dididi_papa
     * @date: 2025/6/24 下午7:03
     * @param: [ids] :采购单id
     * @return: void
     **/
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
                    PurchaseEntity entity = this.getById(id);
                    return entity;
                }).filter(entity -> entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(entity -> {
                    entity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    entity.setUpdateTime(new Date());
                    return entity;
                })
                .collect(Collectors.toList());
        //2.改变采购单状态
        this.updateBatchById(collect);
        //3.改变采购项状态
        collect.forEach(entity -> {
            List<PurchaseDetailEntity> entities =  purchaseDetailService.listDetailByPurchaseId(entity.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });

    }

    @Transactional(noRollbackFor = {OpenFeignException.class})
    @Override
    public void done(PurchaseDoneVo doneVo) {
        Long id = doneVo.getId();
        //1.改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        for (PurchaseItemDoneVo item : doneVo.getItems()) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag =false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
                detailEntity.setReason(item.getReason());
            }
            else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.发送消息给库存系统
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);
        //2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        purchaseService.updateById(purchaseEntity);

    }

}